/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Soligee.view;

import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlCommandLink;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectedData;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectionItems;
import com.icesoft.faces.component.jsfcl.data.DefaultTableDataModel;
import com.icesoft.faces.component.panelpopup.PanelPopup;
import com.icesoft.faces.component.selectinputdate.SelectInputDate;
import com.sun.rave.faces.converter.SqlDateConverter;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import javax.faces.FacesException;
import Soligee.Teste2;
import Soligee.controller.facade.sessionFacadeImplements.SessionFacadeBuscarImplements;
import Soligee.controller.facade.sessionFacadeImplements.SessionFacadeCadastrarImplements;
import Soligee.decorador.PaginacaoListaDezEmDez;
import Soligee.model.vo.lancamentos.LancamentoCaixaVO;
import java.util.Date;
import java.util.List;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version MovimentoCaixa.java
 * @version Created on 01/09/2010, 14:26:04
 * @author LAS
 */

public class MovimentoCaixa extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private DefaultTableDataModel dataTable1Model = new DefaultTableDataModel();
    private List<LancamentoCaixaVO> listaDeLancamentos;
    private static PaginacaoListaDezEmDez paginacaoBusca;

    public static PaginacaoListaDezEmDez getPaginacaoBusca() {
        return paginacaoBusca;
    }

    public static void setPaginacaoBusca(PaginacaoListaDezEmDez paginacaoBusca) {
        MovimentoCaixa.paginacaoBusca = paginacaoBusca;
    }

    public List<LancamentoCaixaVO> getListaDeLancamentos() {
        return listaDeLancamentos;
    }

    public void setListaDeLancamentos(List<LancamentoCaixaVO> listaDeLancamentos) {
        this.listaDeLancamentos = listaDeLancamentos;
    }
    

    public DefaultTableDataModel getDataTable1Model() {
        return dataTable1Model;
    }

    public void setDataTable1Model(DefaultTableDataModel dtdm) {
        this.dataTable1Model = dtdm;
    }
    private PanelPopup panelPopup = new PanelPopup();

    public PanelPopup getPanelPopup() {
        return panelPopup;
    }

    public void setPanelPopup(PanelPopup pp) {
        this.panelPopup = pp;
    }
    private HtmlInputText campoCodLancamento = new HtmlInputText();

    public HtmlInputText getCampoCodLancamento() {
        return campoCodLancamento;
    }

    public void setCampoCodLancamento(HtmlInputText hit) {
        this.campoCodLancamento = hit;
    }
    private HtmlInputText campoDescricao = new HtmlInputText();

    public HtmlInputText getCampoDescricao() {
        return campoDescricao;
    }

    public void setCampoDescricao(HtmlInputText hit) {
        this.campoDescricao = hit;
    }
 
    private HtmlInputText campoCredito = new HtmlInputText();

    public HtmlInputText getCampoCredito() {
        return campoCredito;
    }

    public void setCampoCredito(HtmlInputText hit) {
        this.campoCredito = hit;
    }
    private HtmlInputText campoOperacao = new HtmlInputText();

    public HtmlInputText getCampoOperacao() {
        return campoOperacao;
    }

    public void setCampoOperacao(HtmlInputText hit) {
        this.campoOperacao = hit;
    }
    private HtmlCommandLink tx_opCancelarAba01 = new HtmlCommandLink();

    public HtmlCommandLink getTx_opCancelarAba01() {
        return tx_opCancelarAba01;
    }

    public void setTx_opCancelarAba01(HtmlCommandLink hcl) {
        this.tx_opCancelarAba01 = hcl;
    }
    private HtmlCommandLink link_Cadastrar = new HtmlCommandLink();

    public HtmlCommandLink getLink_Cadastrar() {
        return link_Cadastrar;
    }

    public void setLink_Cadastrar(HtmlCommandLink hcl) {
        this.link_Cadastrar = hcl;
    }
    private DefaultSelectedData selectOneMenu1Bean = new DefaultSelectedData();

    public DefaultSelectedData getSelectOneMenu1Bean() {
        return selectOneMenu1Bean;
    }

    public void setSelectOneMenu1Bean(DefaultSelectedData dsd) {
        this.selectOneMenu1Bean = dsd;
    }
    private DefaultSelectionItems selectOneMenu1DefaultItems = new DefaultSelectionItems();

    public DefaultSelectionItems getSelectOneMenu1DefaultItems() {
        return selectOneMenu1DefaultItems;
    }

    public void setSelectOneMenu1DefaultItems(DefaultSelectionItems dsi) {
        this.selectOneMenu1DefaultItems = dsi;
    }
    private HtmlSelectOneMenu comboTipoOperacao = new HtmlSelectOneMenu();

    public HtmlSelectOneMenu getComboTipoOperacao() {
        return comboTipoOperacao;
    }

    public void setComboTipoOperacao(HtmlSelectOneMenu hsom) {
        this.comboTipoOperacao = hsom;
    }
    private PanelPopup painelPopUpAviso = new PanelPopup();

    public PanelPopup getPainelPopUpAviso() {
        return painelPopUpAviso;
    }

    public void setPainelPopUpAviso(PanelPopup pp) {
        this.painelPopUpAviso = pp;
    }
    private HtmlOutputText tx_popUpAviso = new HtmlOutputText();

    public HtmlOutputText getTx_popUpAviso() {
        return tx_popUpAviso;
    }

    public void setTx_popUpAviso(HtmlOutputText hot) {
        this.tx_popUpAviso = hot;
    }
    private HtmlCommandButton btn_popUpAviso1 = new HtmlCommandButton();

    public HtmlCommandButton getBtn_popUpAviso1() {
        return btn_popUpAviso1;
    }

    public void setBtn_popUpAviso1(HtmlCommandButton hcb) {
        this.btn_popUpAviso1 = hcb;
    }
    private HtmlCommandButton btn_popUpAviso2 = new HtmlCommandButton();

    public HtmlCommandButton getBtn_popUpAviso2() {
        return btn_popUpAviso2;
    }

    public void setBtn_popUpAviso2(HtmlCommandButton hcb) {
        this.btn_popUpAviso2 = hcb;
    }
    private HtmlCommandButton dataTable1FooterLastButton = new HtmlCommandButton();

    public HtmlCommandButton getDataTable1FooterLastButton() {
        return dataTable1FooterLastButton;
    }

    public void setDataTable1FooterLastButton(HtmlCommandButton hcb) {
        this.dataTable1FooterLastButton = hcb;
    }
    private HtmlCommandButton dataTable1FooterFirstButton = new HtmlCommandButton();

    public HtmlCommandButton getDataTable1FooterFirstButton() {
        return dataTable1FooterFirstButton;
    }

    public void setDataTable1FooterFirstButton(HtmlCommandButton hcb) {
        this.dataTable1FooterFirstButton = hcb;
    }
    private HtmlCommandButton dataTable1FooterPreviousButton = new HtmlCommandButton();

    public HtmlCommandButton getDataTable1FooterPreviousButton() {
        return dataTable1FooterPreviousButton;
    }

    public void setDataTable1FooterPreviousButton(HtmlCommandButton hcb) {
        this.dataTable1FooterPreviousButton = hcb;
    }
    private HtmlCommandButton dataTable1FooterNextButton = new HtmlCommandButton();

    public HtmlCommandButton getDataTable1FooterNextButton() {
        return dataTable1FooterNextButton;
    }

    public void setDataTable1FooterNextButton(HtmlCommandButton hcb) {
        this.dataTable1FooterNextButton = hcb;
    }
    private SelectInputDate dataVenda = new SelectInputDate();

    public SelectInputDate getDataVenda() {
        return dataVenda;
    }

    public void setDataVenda(SelectInputDate sid) {
        this.dataVenda = sid;
    }
    private SqlDateConverter sqlDateConverter1 = new SqlDateConverter();

    public SqlDateConverter getSqlDateConverter1() {
        return sqlDateConverter1;
    }

    public void setSqlDateConverter1(SqlDateConverter sdc) {
        this.sqlDateConverter1 = sdc;
    }
    private HtmlInputText totalCaixa = new HtmlInputText();

    public HtmlInputText getTotalCaixa() {
        return totalCaixa;
    }

    public void setTotalCaixa(HtmlInputText hit) {
        this.totalCaixa = hit;
    }
    private HtmlCommandButton panelLayoutLogo = new HtmlCommandButton();

    public HtmlCommandButton getPanelLayoutLogo() {
        return panelLayoutLogo;
    }

    public void setPanelLayoutLogo(HtmlCommandButton hcb) {
        this.panelLayoutLogo = hcb;
    }
    private HtmlCommandButton btn_voltar = new HtmlCommandButton();

    public HtmlCommandButton getBtn_voltar() {
        return btn_voltar;
    }

    public void setBtn_voltar(HtmlCommandButton hcb) {
        this.btn_voltar = hcb;
    }

    // </editor-fold>

    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public MovimentoCaixa() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        inicializaCampos();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("MovimentoCaixa Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected SessionBean1 getview$SessionBean1() {
        return (SessionBean1) getBean("view$SessionBean1");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected ApplicationBean1 getview$ApplicationBean1() {
        return (ApplicationBean1) getBean("view$ApplicationBean1");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected Teste2 getTeste2() {
        return (Teste2) getBean("Teste2");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected Util getview$Util() {
        return (Util) getBean("view$Util");
    }

    /**
     * <p>Retornar uma referência para o Bean de dados limitados.</p>
     *
     * @retorna uma referência para o bean de dados limitados
     */
    protected RequestBean1 getview$RequestBean1() {
        return (RequestBean1) getBean("view$RequestBean1");
    }

    public void inicializaCampos (){
        painelPopUpAviso.setRendered(false);
        campoCodLancamento.resetValue();
        campoCodLancamento.setReadonly(true);
        campoCodLancamento.setValue(getProximoCodigo());
        campoCredito.setValue(0);
        campoDescricao.resetValue();
        campoOperacao.resetValue();
        selectOneMenu1DefaultItems.clear();
        selectOneMenu1DefaultItems.add(new SelectItem (1,"Débito"));
        selectOneMenu1DefaultItems.add(new SelectItem (2,"Crédito"));
        atualizaTabelaLancamentos(new Date());

    }
    public int getProximoCodigo(){
        SessionFacadeBuscarImplements facadeBusca = new SessionFacadeBuscarImplements();
        return facadeBusca.totalDeRegistros(LancamentoCaixaVO.class)+1;
    }
    public String dataTable1_firstPageAction() {
         {
            dataTable1Model.setWrappedData(MovimentoCaixa.getPaginacaoBusca().firstPage());
            dataTable1FooterFirstButton.setDisabled(true);
            dataTable1FooterPreviousButton.setDisabled(true);
            if (MovimentoCaixa.getPaginacaoBusca().getTotalPaginas() > 1) {
                dataTable1FooterNextButton.setDisabled(false);
                dataTable1FooterLastButton.setDisabled(false);
            }
            return null;
        }
    }

    public String dataTable1_previousPageAction() {
        dataTable1Model.setWrappedData(MovimentoCaixa.getPaginacaoBusca().previousPage());
        if (MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina() == 1) {
            dataTable1FooterNextButton.setDisabled(true);
            dataTable1FooterFirstButton.setDisabled(true);
            dataTable1FooterPreviousButton.setDisabled(true);
        }
        if (MovimentoCaixa.getPaginacaoBusca().getTotalPaginas() > 1) {
            dataTable1FooterNextButton.setDisabled(false);
            dataTable1FooterLastButton.setDisabled(false);
        }
        if (MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina() >= 2) {
            dataTable1FooterFirstButton.setDisabled(false);
        }
        return null;
    }

    public String dataTable1_nextPageAction() {
            {
                dataTable1Model.setWrappedData(MovimentoCaixa.getPaginacaoBusca().nextPage());
                dataTable1FooterPreviousButton.setDisabled(false);
                if (MovimentoCaixa.getPaginacaoBusca().getTotalPaginas() == MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina()) {
                    dataTable1FooterNextButton.setDisabled(true);
                    dataTable1FooterLastButton.setDisabled(true);
                }
                if (MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina() >= 2) {
                    dataTable1FooterFirstButton.setDisabled(false);
                }
                return null;
            }
        }

    public String dataTable1_lastPageAction() {
        dataTable1Model.setWrappedData(MovimentoCaixa.getPaginacaoBusca().lastPage());
        if (MovimentoCaixa.getPaginacaoBusca().getTotalPaginas() == MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina()) {
            dataTable1FooterLastButton.setDisabled(true);
            dataTable1FooterNextButton.setDisabled(true);
            dataTable1FooterPreviousButton.setDisabled(false);
            dataTable1FooterFirstButton.setDisabled(false);
        }
        if (MovimentoCaixa.getPaginacaoBusca().getNumeroDaPagina() >= 2) {
            dataTable1FooterFirstButton.setDisabled(false);
        }
        return null;
    }

    public String tx_opCancelarAba01_action() {
        //return null means stay on the same page
        inicializaCampos();
        return null;
    }

    public String link_Cadastrar_action() throws Exception {
        //return null means stay on the same page
        controlaPopup(true, "Cadastrar Lançamento?", true, true, "Sim", "Não");
        return null;
    }
    public void controlaPopup(boolean renderedPopup, String textoPoup, boolean btn1Rendered, boolean btn2Rendered,
           String textobtn1, String textobtn2) {

      painelPopUpAviso.setRendered(renderedPopup);
      tx_popUpAviso.setValue(textoPoup);
      btn_popUpAviso1.setValue(textobtn1);
      btn_popUpAviso1.setRendered(btn1Rendered);
      btn_popUpAviso2.setRendered(btn2Rendered);
      btn_popUpAviso2.setValue(textobtn2);
   }
   
    public boolean validaCamposVazios(){
        if (campoCodLancamento.getValue().toString().equals(""))
            return false;
        if (campoDescricao.getValue().toString().equals(""))
            return false;
        if (comboTipoOperacao.getValue().toString().equals(""))
            return false;
        return true;
    }
    public String btn_popUpAviso1_action() throws Exception {
        if (validaCamposVazios()){
            SessionFacadeCadastrarImplements facadeCadastrar = new SessionFacadeCadastrarImplements();
            if (Integer.parseInt(comboTipoOperacao.getValue().toString())==1){
                facadeCadastrar.cadastrarLancamentoCaixa(campoDescricao.getValue().toString(), Double.parseDouble(campoCredito.getValue().toString()), 0, Integer.parseInt(comboTipoOperacao.getValue().toString()));
            }
            else if (Integer.parseInt(comboTipoOperacao.getValue().toString())==2){
                facadeCadastrar.cadastrarLancamentoCaixa(campoDescricao.getValue().toString(), 0, Double.parseDouble(campoCredito.getValue().toString()), Integer.parseInt(comboTipoOperacao.getValue().toString()));
            }
            controlaPopup(true, "Lançamento Cadastrado com sucesso!", false, true, "", "Ok");
            inicializaCampos();
        } else
            controlaPopup(true, "Campos Obrigatórios em branco", false, true, "", "Ok");
        
        return null;
    }

    public String btn_popUpAviso2_action() {
        painelPopUpAviso.setRendered(false);
        return null;
    }

    public void comboTipoOperacao_processValueChange(ValueChangeEvent vce) {}

    public void atualizaTabelaLancamentos(Date data){
            totalCaixa.resetValue();
            SessionFacadeBuscarImplements facadeBusca = new SessionFacadeBuscarImplements();
            this.setListaDeLancamentos(facadeBusca.buscarPorData(data, "codLancamento",LancamentoCaixaVO.class));
            dataTable1Model.setWrappedData(getListaDeLancamentos());
            this.setPaginacaoBusca(new PaginacaoListaDezEmDez(this.getListaDeLancamentos()));
            this.controlaPaginacao(this.getListaDeLancamentos().size());
            double total = facadeBusca.buscarSoma(data, "credito", LancamentoCaixaVO.class) - facadeBusca.buscarSoma(data, "debito", LancamentoCaixaVO.class);
            totalCaixa.setValue(total);
            System.out.println(total);
    }

    public void dataVenda_processValueChange(ValueChangeEvent vce) {
        Date dataCaixa = (Date) (Object) dataVenda.getValue();
        atualizaTabelaLancamentos(dataCaixa);
    }

    public void controlaPaginacao(int controlePaginas) {
      if (controlePaginas <= 10) {
         dataTable1FooterFirstButton.setDisabled(true);
         dataTable1FooterPreviousButton.setDisabled(true);
         dataTable1FooterNextButton.setDisabled(true);
         dataTable1FooterLastButton.setDisabled(true);
      }
      if (controlePaginas > 10) {
         dataTable1FooterNextButton.setDisabled(false);
         dataTable1FooterLastButton.setDisabled(false);
         dataTable1FooterFirstButton.setDisabled(true);
         dataTable1FooterPreviousButton.setDisabled(true);
      }
    }

    public String panelLayoutLogo_action() {
        //return null means stay on the same page
        return "voltar";
    }

    public String btn_voltar_action() {
        //return null means stay on the same page
        return "voltar";
    }

}

